/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, RawMeasureResult } from '@amcax/base';
import { parseMeasureResult } from '@app-base/common/utils/measure';
import { getIdOfPickedObj } from '@app-base/common/utils/render';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2 } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { FeatureBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { gbT1962003 } from './gbt196-2003';

enum Mode {
  DISTANCE = 'distance',
  FULL = 'full',
  TOPLANE = 'toplane',
}

enum Standard {
  NONSTANDARD = 'nonstandard',
  GB_T_196_2003 = 'GB/T 196-2003',
}

type FormDataType = {
  face: pickedFaceData;
  plane: pickedFaceData;
  standard: string;
  diameter: number;
  mode: Mode;
  toplane?: pickedFaceData;
  distance?: number;
  turnheight: number;
  leftup: boolean;
  standardNumber?: string;
  minorDiameter?: number;
  reverse?: boolean;
};

function Thread({ title, onClose, props }: FeaturedCmdDialogParams) {
  const [formData, setFormData] = useState<FormDataType>({
    face: null,
    plane: null,
    standard: Standard.NONSTANDARD,
    diameter: 0,
    mode: Mode.DISTANCE,
    toplane: null,
    distance: 10,
    turnheight: 1,
    leftup: false,
    standardNumber: '',
    minorDiameter: 0,
    reverse: false,
  });
  const [faceDiameter, setFaceDiameter] = useState<number>(0);

  const { picker } = useTools();

  const calculateFaceDiameter = async () => {
    const face = formData.face;
    if (face) {
      const faceObj = getIdOfPickedObj(face);
      const result: RawMeasureResult = await wsApi.measure(faceObj, '', true);
      const parsedResult = parseMeasureResult(result);
      const diameter = (parsedResult?.radius?.value ?? 0) * 2;
      setFaceDiameter(diameter);
      setFormData({
        ...formData,
        diameter,
        ...(diameter !== formData.diameter
          ? { standard: Standard.NONSTANDARD }
          : {}),
      });
    }
  };

  useEffect(() => {
    calculateFaceDiameter();
  }, [formData.face]);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const face = props?.params?.face;
      const plane = props?.params?.plane;
      const standard = props?.params?.standard;
      const diameter = props?.params?.diameter;
      const mode = props?.params?.mode;
      const toplane = props?.params?.toplane;
      const distance = props?.params?.distance;
      const turnheight = props?.params?.turnheight;
      const leftup = props?.params?.leftup;
      const standardNumber = props?.params?.standardNumber;
      const minorDiameter = props?.params?.minorDiameter;
      const reverse = props?.params?.reverse;

      await initEditDependency([face, plane, standard, mode]);

      setFormData({
        face: picker.generatePickObjByPickID(face) as pickedFaceData,
        plane: picker.generatePickObjByPickID(plane) as pickedFaceData,
        standard: standard,
        diameter: diameter,
        mode: mode,
        ...(toplane
          ? {
              toplane: picker.generatePickObjByPickID(
                toplane,
              ) as pickedFaceData,
            }
          : {}),
        distance: distance,
        turnheight: turnheight,
        leftup: leftup,
        standardNumber: standardNumber,
        minorDiameter: minorDiameter,
        reverse: reverse,
      });
    }
  }, []);

  const isFormDataValid = () => {
    const {
      face,
      plane,
      distance,
      turnheight,
      toplane,
      leftup,
      diameter,
      mode,
    } = formData;
    if (mode === Mode.FULL) {
      return (
        face !== null &&
        plane !== null &&
        turnheight !== null &&
        leftup !== null &&
        diameter >= faceDiameter
      );
    }
    if (mode === Mode.TOPLANE) {
      return (
        face !== null &&
        plane !== null &&
        toplane !== null &&
        turnheight !== null &&
        leftup !== null &&
        diameter >= faceDiameter
      );
    }
    return (
      face !== null &&
      plane !== null &&
      distance !== null &&
      turnheight !== null &&
      leftup !== null &&
      diameter >= faceDiameter
    );
  };

  const finishValid = useMemo(isFormDataValid, [formData]);
  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-thread', {
      commandName: 'CreateThread',
      editDxid: props?.shape || props?.dxid,
      onClose,
      finishDraw: checkAndFinish,
    });

  const execute = async (preview: boolean) => {
    const {
      face,
      plane,
      standard,
      diameter,
      mode,
      toplane,
      distance,
      turnheight,
      leftup,
      standardNumber,
      minorDiameter,
      reverse,
    } = formData;

    await confirmCommand(
      {
        a: {
          face: face?.meshId,
          plane: plane?.meshId,
          standard: standard,
          diameter: diameter,
          mode: mode,
          toplane: toplane?.meshId,
          distance: distance,
          turnheight: turnheight,
          leftup: leftup,
          standardNumber: standardNumber,
          minorDiameter: minorDiameter,
          reverse: reverse,
        },
      },
      preview,
      (err) => {
        if (err?.code === 601 && err?.message === 'only support cylinder') {
          MessageTip.destroy();
          MessageTip.warning('支持面仅支持圆柱面');
        }
      },
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);

    ctx2.viewer.requestRender();
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        face: {
          type: 'string',
          title: '支持面',
          format: PickInputRJSFFormat.PickSurface,
        },
        plane: {
          type: 'string',
          title: '限制面',
          format: PickInputRJSFFormat.PickPlane,
        },
        reverse: {
          type: 'boolean',
          title: '反转',
          default: false,
        },
        faceDiameter: {
          type: 'number',
          title: '支持面直径',
          format: NumberInputFormat.Length,
          default: 0,
        },
        standard: {
          type: 'string',
          title: '标准螺纹',
          oneOf: [
            {
              type: 'string',
              title: '非标准',
              const: Standard.NONSTANDARD,
            },
            {
              type: 'string',
              title: Standard.GB_T_196_2003,
              const: Standard.GB_T_196_2003,
            },
          ],
          default: Standard.NONSTANDARD,
        },
        ...(formData.standard !== Standard.NONSTANDARD
          ? {
              standardNumber: {
                type: 'string',
                title: '螺纹型号',
                oneOf: Object.keys(gbT1962003)
                  .filter(
                    (key) => gbT1962003[key].majorDiameter === faceDiameter,
                  )
                  .map((key) => ({
                    type: 'string',
                    title: key,
                    const: key,
                  })),
                default:
                  Object.keys(gbT1962003).filter(
                    (key) => gbT1962003[key].majorDiameter === faceDiameter,
                  )?.[0] ?? '',
              },
              minorDiameter: {
                type: 'number',
                title: '小径',
                format: NumberInputFormat.Length,
                default: 0,
              },
            }
          : {}),
        ...(formData.standard === Standard.NONSTANDARD
          ? {
              diameter: {
                type: 'number',
                title: '螺纹直径',
                format: NumberInputFormat.Length,
                default: 0,
              },
            }
          : {}),
        mode: {
          type: 'string',
          title: '螺纹模式',
          default: Mode.DISTANCE,
          oneOf: [
            {
              type: 'string',
              title: '尺寸',
              const: Mode.DISTANCE,
            },
            {
              type: 'string',
              title: '支持面深度',
              const: Mode.FULL,
            },
            {
              type: 'string',
              title: '直到平面',
              const: Mode.TOPLANE,
            },
          ],
        },
        ...(formData.mode === Mode.DISTANCE
          ? {
              distance: {
                type: 'number',
                title: '螺纹深度',
                format: NumberInputFormat.Length,
              },
            }
          : {}),
        ...(formData.mode === Mode.TOPLANE
          ? {
              toplane: {
                type: 'string',
                title: '直到平面',
                format: PickInputRJSFFormat.PickPlane,
              },
            }
          : {}),
        turnheight: {
          type: 'number',
          title: '螺距',
          format: NumberInputFormat.Length,
        },
        leftup: {
          type: 'string',
          title: '螺纹面',
          oneOf: [
            // 暂时不支持左旋螺纹
            // {
            //   type: 'boolean',
            //   title: '左旋螺纹',
            //   const: true,
            // },
            {
              type: 'boolean',
              title: '右旋螺纹',
              const: false,
            },
          ],
          default: false,
        },
      },
      (val) => val == null,
    );
    return {
      type: 'object',
      properties,
    } as RJSFSchema;
  }, [formData.standard, formData.mode, faceDiameter]);

  const finalFormData = useMemo(
    () => ({
      ...formData,
      faceDiameter: faceDiameter,
    }),
    [formData, faceDiameter],
  );

  return (
    <PickableCommandForm
      title={title}
      className='-mt-3'
      onClose={onClose}
      disabled={initingEdit}
      submitLoading={isLoading}
      isFormDataValid={finishValid}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        if (v.standard !== Standard.NONSTANDARD) {
          const standardNumber = Object.keys(gbT1962003).filter(
            (key) => gbT1962003[key].majorDiameter === faceDiameter,
          );
          if (standardNumber.length > 0) {
            v.standardNumber = v.standardNumber
              ? v.standardNumber
              : standardNumber[0];
            v.minorDiameter = gbT1962003?.[v.standardNumber]?.minorDiameter;
            v.turnheight = gbT1962003?.[v.standardNumber]?.pitch;
            v.leftup = false;
          } else {
            v.standard = Standard.NONSTANDARD;
            MessageTip.warning('该直径下没有找到对应的螺纹型号');
          }
        }
        setFormData(v);
      }}
      extraUiSchema={{
        face: {
          'ui:placeholder': '请输入圆柱面',
          'ui:autofocus': true,
        },
        plane: {
          'ui:placeholder': '请输入平面',
        },
        reverse: {
          'ui:widget': 'checkbox',
        },
        toplane: {
          'ui:placeholder': '请输入平面',
          'ui:options': {
            pickFilter: (obj) => {
              if (obj?.meshId === formData.plane?.meshId) {
                MessageTip.warning('不能选择与限制面相同的平面');
                return false;
              }
              return true;
            },
          },
        },
        standard: {
          'ui:disabled': !formData.face,
        },
        diameter: {
          'ui:disabled': true,
        },
        faceDiameter: {
          'ui:disabled': true,
        },
        minorDiameter: {
          'ui:disabled': true,
        },
        turnheight: {
          'ui:disabled': formData.standard !== Standard.NONSTANDARD,
        },
        leftup: {
          'ui:disabled': formData.standard !== Standard.NONSTANDARD,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdThread: FeatureBaseCommand = {
  id: 'CmdThread',
  label: 'command.thread',
  icon: 'commands/feature/thread',
  create: (label, onClose, props) => (
    <Thread
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};

export const cmdThreadInner: FeatureBaseCommand = {
  id: 'CmdThreadInner',
  label: 'command.thread',
  icon: 'commands/feature/thread-inner',
  create: (label, onClose, props) => (
    <Thread
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
